<template>
  <div class="login-container">
    <el-form status-icon
             label-position="left"
             label-width="0px"
             class="demo-ruleForm login-page">
      <h3 class="title">注册账号</h3>
      <el-form label-position="left" label-width="80px" :model="formLabelAlign">
        <el-form-item label="姓名:">
          <el-input v-model="formLabelAlign.name"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formLabelAlign.id"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formLabelAlign.password"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="formLabelAlign.phone"></el-input>
        </el-form-item>
      </el-form>
      <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
      <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
      <div v-if="imgSrc" class="img_bg_camera">
        <p>效果预览</p>
        <img :src="imgSrc" alt class="tx_img" />
      </div>
      <div class="button">
        <el-button @click="getCompetence()">打开摄像头</el-button>
        <el-button @click="stopNavigator()">关闭摄像头</el-button>
        <el-button @click="setImage()">拍照</el-button>
      </div>
      <el-form-item style="width:100%;">
        <el-button type="primary" style="width:100%;" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import {registerAccount} from "../../api/data";

export default {
  data() {
    return {
      videoWidth: 350,
      videoHeight: 240,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo:false,
      formLabelAlign: {
        name: '',
        id: '',
        password: '',
        phone: ''
      }
    }
  },
  methods: {
    handleSubmit(){
      let registerMsg={
        uid: this.formLabelAlign.id,
        pwd: this.formLabelAlign.password,
        username: this.formLabelAlign.name,
        rid: 1,
        phone: this.formLabelAlign.phone,
        image: this.imgSrc
      }
      registerAccount(JSON.stringify(registerMsg)).then(res=>{
        if (res.data.code === 0) {
          this.$message({
            message: '提交成功，即将返回首页',
            type: 'success'
          });
          setTimeout(this.quitExam, 2000);
          this.stopNavigator();
        } else {
          this.$message.error('提交失败');
        }
      });
    },
    quitExam(){
      //这里返回到登录界面
      this.$router.replace('/')
    },
    // 调用权限（打开摄像头功能）
    getCompetence() {
      let _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = 'block';
      // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {//不存在则报错
            return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      let constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)"
        }
      };
      navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function(stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function() {
              _this.thisVideo.play();
            };
          })
          .catch(err => {
            console.log(err);
          });
    },
    //  绘制图片（拍照功能）
    setImage() {
      let _this = this;
      // canvas画图
      _this.thisContext.drawImage(
          _this.thisVideo,
          0,
          0,
          _this.videoWidth,
          _this.videoHeight
      );
      // 获取图片base64链接
      let image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image;//赋值并预览图片
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
    // base64转文件，此处没用到
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
};
</script>

<style scoped>
.login-container {
  background:url('../../src/assets/images/registerBack.png');

  background-size:100% 100%;
  width: 100%;
  height: 135%;
}

.title {
  margin-top: auto;
  text-align: center;
}

.login-page {
  -webkit-border-radius: 5px;
  border-radius: 5px;
  margin: auto auto;
  width: 350px;
  padding: 35px 35px 15px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
}

label.el-checkbox.rememberMe {
  margin: 0px 0px 15px;
  text-align: left;
}
</style>
